# 读取脚本文件下的文件，
import AutoTesting.settings as s
from jinja2 import Template
import xlrd
import os

def getExcel():
	path = (s.T99SCRIPT)
	files = list(filter(lambda x:x.endswith(s.T01EXTENSION) ,os.listdir(path)))
	return list(map(lambda x:os.path.join(path,x),files))

class Excel:
	excels = []
	parameters = {}
	sheetName = s.T01SHEETNAME
	parameterSheetName = s.T01PARAMETERSHEETNAME
	identification = s.T01ID
	target = s.T01OBJECT
	location = s.T01LOCATION
	operate = s.T01OPERATE
	value = s.T01VALUE
	temporary_value_key = None
	temporary_keys = []


	@classmethod
	def __parse(cls,rowData):
		if len(rowData)==5:
			d = rowData
		elif len(rowData)>5:
			d = rowData[:5]
		else:
			d = rowData
			for i in range(len(rowData),5):
				d.append("")
		d = list(map(lambda x:str(x).strip(),d))
		d[0] = (d[0]) if d[0]!="" else "-1"
		return d

	@classmethod
	def readData(cls,sheet):
		def readExcelData():
			for i in range(s.T01STARTROW-1,sheet.nrows):
				d = (cls.__parse(sheet.row_values(i)))
				yield d
		return readExcelData()

	@classmethod
	def readExcel(cls,filename):
		wb = xlrd.open_workbook(filename)
		sheet = wb.sheet_by_name(cls.sheetName)
		cls.excels.append([filename,sheet,cls.readData(sheet)])
		parameterSheet = wb.sheet_by_name(cls.parameterSheetName)
		cls.setParameter(parameterSheet)

	@classmethod
	def setParameter(cls,sheetname):
		for i in range(s.T01STARTPARAMETERROW-1,sheetname.nrows):
			p = sheetname.row_values(i)
			if p[s.T02PARAMETERYTYPE].strip()=='dict':
				cls.temporary_value_key = str(p[s.T01PARAMETERKEY]).strip()
				cls.__set_parameter_key(p)
			elif (p[s.T01PARAMETERKEY].strip()=='' and p[s.T02PARAMETERYTYPE].strip()=='' and p[s.T01PARAMETERVALUE]==''):
				cls.__parse_parameter_value(p)
			else:
				key = str(p[s.T01PARAMETERKEY]).strip()
				value = str(p[s.T01PARAMETERVALUE])
				cls.parameters[key] = value

	@classmethod
	def __parse_parameter_value(cls,data):
		values = data[s.T01PARAMETERSTARTLOCATION-1:]
		d = {}
		for key,value in zip(cls.temporary_keys,values):
			d[key] = value
		cls.parameters[cls.temporary_value_key].append(d)

	@classmethod
	def __set_parameter_key(cls,data):
		cls.parameters[cls.temporary_value_key] = []
		cls.temporary_keys = []
		for d in data[s.T01PARAMETERSTARTLOCATION-1:]:
			if d.strip()!="":
				cls.temporary_keys.append(d.strip())
			else:
				break


	@classmethod
	def loadExcel(cls,filename):
		excelName = os.path.join(s.T99SCRIPT,filename)
		cls.readExcel(excelName)
		return None

	@classmethod
	def funLabel(cls,label):
		return label.strip()

	@classmethod
	def _parse(cls,rowData):
		data = False
		if rowData[s.T01OPERATE].strip() in s.T01INSTRUCTIONS:
			instructions = s.T01INSTRUCTIONS[rowData[s.T01OPERATE].strip()]%rowData[s.T01VALUE]
			data = eval(instructions)
		return data

	@classmethod
	def readContent(cls):
		while len(cls.excels)!=0:
			try:
				data = next(cls.excels[-1][s.T01READDATAFUN])
				data.insert(0,cls.excels[-1][0])
				returnData = cls._parse(data)
				if returnData:
					data = returnData
				elif returnData is None:
					continue
			except StopIteration as e:
				cls.excels.pop()
				continue
			yield data

	@classmethod
	def readBefor(cls):
		contents = cls.readContent()
		texts = []
		for text in contents:
			if type(text) is str:
				texts.append(text.strip())
			elif type(text) is list:
				texts.append(s.T03SPLIT_FILED.join(text))
		return texts

	@classmethod
	def readAfter(cls):
		datas = cls.readBefor()
		text = ""
		for data in datas:
			if s.T03SPLIT_FILED in data:
				text = text+s.T03SPLIT_ROW+data
			else:
				text = text+data
		if text.startswith(s.T03SPLIT_ROW):
			text = text[len(s.T03SPLIT_ROW):]
		return text

def read():
	Excel.readExcel(s.T99RUNFILE)
	text = Excel.readAfter()
	template = Template(text)
	text = template.render(**Excel.parameters)
	text = text.strip(s.T03SPLIT_ROW)
	data = []
	text = text.split(s.T03SPLIT_ROW)
	for t in text:
		data.append(t.split(s.T03SPLIT_FILED))
	return (data)











